<?php 
/**
* Login Controller
*/
class LoginController extends CI_Controller
{
	
	function __construct()
	{
		parent::__construct();
    	$this->load->model('Employee_Model');
    	$this->load->model('utility_model');
	}

	public function index(){

		$this->load->view("login");
	}

	public function login(){

		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_checkLogin');
		$this->form_validation->set_message('required','กรุณาใส่ %s ');

		if($this->form_validation->run() == FALSE)
		{
		 //Field validation failed.  User redirected to login page
		 $this->load->view('login');
		}
		else
		{
		 //Go to private area
		 redirect('mainController', 'refresh');
		}

		
	}

	public function checkLogin(){
		$username = $this->input->post('username');
		$password = $this->input->post('password');

		//echo "work --".$username."----".$password."---";
		$rs = $this->Employee_Model->checkUser($username);

		if( $rs->num_rows() > 0){
			$rowData = $rs->row_array(); 

			//Check Status
			if($rowData['emp_status'] == 'N'){
				$this->Employee_Model->updateFailcount($rowData['id'],$rowData['login_failcount']+1);
				$this->form_validation->set_message('checkLogin', 'กรุณาติดต่อเจ้าหน้าที่');
    		return FALSE;
			}
			//Check FailCount
			if($rowData['login_failcount'] >= 6){
				$this->Employee_Model->updateFailcount($rowData['id'],$rowData['login_failcount']+1);
				$this->form_validation->set_message('checkLogin', 'กรุณาติดต่อเจ้าหน้าที่');
				$this->Employee_Model->changeStatus($rowData['id'],'N');
    		return FALSE;
			}

			//Check Password
			$rs = $this->Employee_Model->checkPasswordOfID($password,$rowData['id']);
			
			if ($rs->num_rows > 0) {

				$row = $rs->row_array();
				$resultUserInfo = $this->Employee_Model->getUserInfo($row['id']);
				$resultPerm = $this->Employee_Model->getPermissionUser($row['id']);

				$resultUserInfo = $this->utility_model->changeToUTF8($resultUserInfo);


	  		$this->session->set_userdata('userdata',$resultUserInfo);
	  		$_SESSION['permission'] = $resultPerm;

				$this->Employee_Model->clearFailcount($row['id']);

				return TRUE;

			}else{
				$this->Employee_Model->updateFailcount($rowData['id'],$rowData['login_failcount']+1);
				$this->form_validation->set_message('checkLogin', 'ข้อมูลไม่ถูกต้อง');
    		return FALSE;
			}
		}else{
			$this->form_validation->set_message('checkLogin', 'ข้อมูลไม่ถูกต้อง');
    	return FALSE;
		}
	}

	public function logout(){
		$this->session->sess_destroy();
		redirect('loginController','refresh');
	}
}
?>